﻿using IT_RoadBlock.Comands;
using IT_RoadBlock.DataContexts;
using IT_RoadBlock.Dto;
using IT_RoadBlock.Entities;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;

namespace IT_RoadBlock.ViewModes
{
    public class ProjectEditViewModel : EditRelayCommand<TProjectInfo>
    {
        public FyDbContext DbContext = new FyDbContext();

        public ProjectEditViewModel(TProjectInfo projectInfo)
        {
            this.CurData = projectInfo;
        }

     

        protected override void SaveItemCmdExecute(TProjectInfo obj)
        {
            StringBuilder sbf = new StringBuilder();
            TProjectInfo curData = this.CurData;
            if (string.IsNullOrWhiteSpace(curData.Name))
            {
                sbf.Append("项目名称不能为空");
            }
            if (string.IsNullOrWhiteSpace(curData.ProjectCode))
            {
                sbf.Append("项目编号不能为空");
            }
            if (string.IsNullOrWhiteSpace(curData.Remark))
            {
                sbf.Append("备注不能为空");
            }

            if (sbf.Length > 0)
            {
                Result result = ResultFactory.Fail(sbf.ToString());
                DialogWindow?.Invoke(this,result);
            }
            else
            {
                IQueryable<TProjectInfo> queryables = DbContext.TProjectInfoDbSet.Where(p => 1 == 1);
                if (curData.Id != null)
                {
                    queryables = queryables.Where(p => p.Id != curData.Id);
                }
                queryables = queryables.Where(p => p.ProjectCode == curData.ProjectCode);

                int count = queryables.Count();
                if (count > 0)
                {
                    Result result = ResultFactory.Fail("当前项目编号已存在");
                    DialogWindow?.Invoke(this, result);
                    return;
                }

                curData.CreateTime = curData.CreateTime??new System.DateTime();
                DbContext.TProjectInfoDbSet.AddOrUpdate(curData);
                DbContext.SaveChanges();
                DialogWindow?.Invoke(this, ResultFactory.Ok());
            }
        }

        ~ProjectEditViewModel()
        {
            DbContext?.Dispose();
        }
    }
}
